package com.ruoyi.resume.utils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Optional;

import org.apache.commons.io.FilenameUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

public class ResumeProcessingUtils {
    private static final Logger logger = LoggerFactory.getLogger(ResumeProcessingUtils.class);

    // 文件类型检测
    public static String detectFileType(MultipartFile file) {
        String fileName = Optional.ofNullable(file.getOriginalFilename())
                .orElseThrow(() -> new IllegalArgumentException("文件名不能为空"))
                .toLowerCase();

        String extension = FilenameUtils.getExtension(fileName);
        switch (extension) {
            case "pdf":
                return "pdf";
            case "docx":
                return "word";
            default:
                throw new IllegalArgumentException("不支持的文件类型: " + fileName);
        }
    }

    // 文本提取统一入口
    public static String extractText(MultipartFile file, String fileType) throws Exception {
        switch (fileType) {
            case "pdf":
                return extractFromPdf(file);
            case "word":
                return extractFromWord(file);
            default:
                throw new IllegalArgumentException("不支持的格式");
        }
    }

    private static String extractFromPdf(MultipartFile file) throws IOException {
        try (PDDocument doc = PDDocument.load(file.getInputStream())) {
            return new PDFTextStripper().getText(doc);
        }
    }

    private static String extractFromWord(MultipartFile file) throws IOException {
        try (XWPFDocument doc = new XWPFDocument(file.getInputStream())) {
            return parseWordDocument(doc);
        }
    }

    private static String parseWordDocument(XWPFDocument doc) {
        StringBuilder sb = new StringBuilder();
        doc.getParagraphs().forEach(p -> sb.append(p.getText()).append("\n"));
        doc.getTables().forEach(table -> table.getRows().forEach(row ->
                row.getTableCells().forEach(cell -> sb.append(cell.getText()).append("\n"))
        ));
        return sb.toString();
    }

    // 文件保存工具方法
    public static Path saveContentToFile(String parentDir, String section, String content) throws IOException {
        Path dirPath = Paths.get(parentDir);
        if (!Files.exists(dirPath)) {
            Files.createDirectories(dirPath);
        }

        String safeFileName = section.replaceAll("[^\\w\\u4e00-\\u9fa5]", "_") + ".txt";
        Path filePath = dirPath.resolve(safeFileName);
        return Files.write(filePath, content.getBytes(StandardCharsets.UTF_8));
    }

    // Markdown清理
    public static String cleanMarkdown(String content) {
        return content.replaceAll("###\\s+", "")
                .replaceAll("[-*_]{2,}", "")
                .trim();
    }
}
